<?php
include_once dirname(__FILE__) . '/function.php';
$func_id = isset($_GET['func_id']) ? trim($_GET['func_id']) : '';
if (!$func_id) {
	throw new Exception('func error');
}
$func_arr = [
	"userList",
	"userAdd",
	"userDetail"
];
if (!in_array($func_id, $func_arr)) {
	throw new Exception('func not exist');
}

/**
 * 用户列表
 */
if ($func_id == 'userList') {
	$userList = Functions::getUser();
	Functions::view('index', ['userList' => $userList]);
}
/**
 * 用戶添加
 */
if ($func_id == 'userAdd') {
	$userName = isset($_POST['userName']) ? trim($_POST['userName']) : '';
	$userKey  = isset($_POST['userKey']) ? trim($_POST['userKey']) : '';
	if (!$userName || !$userKey) {
		Functions::errorMsg('参数缺失');
	}
	$userScript = md5(base64_encode($userKey), false);
	//创建用户私钥
	list($userPrivateKey, $userPublicKey) = Functions::makePrivateKey($userScript);
	list($serverPrivateKey, $serverPublicKey) = Functions::makePrivateKey($userScript);
	$predis = Pcache::create();
	$uid    = $predis->incr(Functions::ID_INCR);
	$predis->sadd(Functions::USER_KEY, $uid);
	$userDetailKey   = sprintf(Functions::USER_DEATIL, $uid);
	$serverDetailKey = sprintf(Functions::SERVER_DEATIL, $uid);
	$predis->hmset($userDetailKey, [
									 "NAME"       => $userName,
									 "KEY"        => $userKey,
									 "SCRIPT"     => $userScript,
									 "PRIVATEKEY" => $userPrivateKey,
									 "PUBLICKEY"  => $userPublicKey['key'],
									 "CREATEAT"   => time()
								 ]
	);

	$predis->hmset($serverDetailKey, [
									   "NAME"       => $userName,
									   "KEY"        => $userKey,
									   "SCRIPT"     => $userScript,
									   "PRIVATEKEY" => $serverPrivateKey,
									   "PUBLICKEY"  => $serverPublicKey['key'],
									   "CREATEAT"   => time()
								   ]
	);
	Functions::errorMsg('success');
}
/**
 * 用户详情
 */
if ($func_id == "userDetail") {
	$userId = isset($_GET['userId']) ? trim($_GET['userId']) : '';
	if (!$userId) {
		Functions::errorMsg('参数缺失');
	}
	$predis          = Pcache::create();
	$userDetailKey   = sprintf(Functions::USER_DEATIL, $userId);
	$serverDetailKey = sprintf(Functions::SERVER_DEATIL, $userId);
	$userDetail      = $predis->HGETALL($userDetailKey);
	$serverDetail    = $predis->HGETALL($serverDetailKey);
	Functions::view('detail', [
								'userDetail'   => $userDetail,
								'serverDetail' => $serverDetail,
							]
	);
}


